package com.example.zsf.fragment;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.zsf.R;
import com.example.zsf.activity.account.AvatarSelectListActivity;
import com.example.zsf.activity.account.LoginActivity;
import com.example.zsf.activity.mine.AboutActivity;
import com.example.zsf.activity.mine.CollectRecordActivity;
import com.example.zsf.activity.mine.MyFavoriteActivity;
import com.example.zsf.activity.mine.ScanActivity;
import com.example.zsf.adapter.MineListAdapter;
import com.example.zsf.base.ZSFGlobal;
import com.example.zsf.message.AccountEventMessage;
import com.example.zsf.model.ItemDataModel;
import com.example.zsf.model.UserModel;
import com.example.zsf.utils.DebouncedOnItemClickListener;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class MineFragment extends Fragment {
    public static final int AvatarSelectRequestCode = 1;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.login_or_out_bt)
    Button loginOrOutBt;
    private Unbinder unbinder;
    private MineListAdapter mineListAdapter;

    ///手机号 id
    private View containerView;


    private int[] avatars = {
            R.mipmap.zhanshi,
            R.mipmap.nvzhanshi,
            R.mipmap.fashi,
            R.mipmap.nvfashi,
            R.mipmap.daoshi,
            R.mipmap.nvdaoshi,
    };

    public MineFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_mine, container, false);
        unbinder = ButterKnife.bind(this, inflate);
        containerView = inflater.inflate(R.layout.header_mine, null);
        initUI();
        return inflate;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        if (requestCode == AvatarSelectRequestCode) {
            int selected = data.getIntExtra("selected", -1);
            CircleImageView view = containerView.findViewById(R.id.circleImageView3);
            if (selected == -1) {
                view.setImageResource(R.mipmap.take_photo);
            } else {
                view.setImageResource(avatars[selected]);
            }
        }

    }

    private void initUI() {
        if (!ZSFGlobal.checkLogoutStatus(new ZSFGlobal.AccountCallBack() {
            @Override
            public void noneauth() {
                containerView.findViewById(R.id.info_container).setVisibility(View.GONE);
                containerView.findViewById(R.id.circleImageView3).setOnClickListener(null);
                loginOrOutBt.setText("立即登录");
            }
        })) {
            UserModel userModel = ZSFGlobal.getUserModel();
            containerView.findViewById(R.id.info_container).setVisibility(View.VISIBLE);
            ((TextView) containerView.findViewById(R.id.nickname_tv)).setText(userModel.getPhone());
            CircleImageView avatarImageView = containerView.findViewById(R.id.circleImageView3);
            int avatarPosition = SPUtils.getInstance().getInt("avatar", -1);
            if (avatarPosition != -1){
                avatarImageView.setImageResource(avatars[avatarPosition]);
            }
            avatarImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), AvatarSelectListActivity.class);
                    startActivityForResult(intent, AvatarSelectRequestCode);
                }
            });

            loginOrOutBt.setText("退出登录");
        }

        List<ItemDataModel> itemDataModels = getItemDatas();
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mineListAdapter = new MineListAdapter(R.layout.item_mine, itemDataModels);

        mineListAdapter.addHeaderView(containerView);


        mineListAdapter.setOnItemClickListener(new DebouncedOnItemClickListener(400) {
            @Override
            public void onDebouncedItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                ItemDataModel selected = (ItemDataModel) adapter.getItem(position);
                switch (selected.type) {
                    case 0: {
                        if (ZSFGlobal.checkLogoutStatus(null)) {
                            jumpToLoginPage();
                            return;
                        }
                        Intent intent = new Intent(getActivity(), MyFavoriteActivity.class);
                        startActivity(intent);
                    }
                    break;
                    case 1: {
                        if (ZSFGlobal.checkLogoutStatus(null)) {
                            jumpToLoginPage();
                            return;
                        }
                        Intent intent = new Intent(getActivity(), CollectRecordActivity.class);
                        startActivity(intent);
                    }
                    break;
                    case 2: {
                        if (ZSFGlobal.checkLogoutStatus(null)) {
                            jumpToLoginPage();
                            return;
                        }
                        if (hasQQ(getActivity())) {
                            String qqUrl = "mqq://im/chat?chat_type=wpa&uin=2913142741&version=1&src_type=web";
                            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(qqUrl)));
                        } else {
                            ToastUtils.showShort("请安装QQ客户端");
                        }
                    }
                    break;
                    case 3: {
                        if (ZSFGlobal.checkLogoutStatus(null)) {
                            jumpToLoginPage();
                            return;
                        }
                        MineFragmentPermissionsDispatcher.jumpToScanActivityWithPermissionCheck(MineFragment.this);
                    }
                    break;
                    case 4: {
                        Intent intent = new Intent(getActivity(), AboutActivity.class);
                        startActivity(intent);
                    }
                    break;
                    default:
                        break;
                }
            }
        });
        recyclerView.setAdapter(mineListAdapter);
    }

    private List<ItemDataModel> getItemDatas() {
        List<ItemDataModel> itemDataModels = new ArrayList<>();
        ItemDataModel itemDataModel = new ItemDataModel();
        itemDataModel.type = 0;
        itemDataModel.icon_id = R.mipmap.favorite;
        itemDataModel.title = "我的关注";
        ItemDataModel itemDataModel1 = new ItemDataModel();
        itemDataModel1.type = 1;
        itemDataModel1.icon_id = R.mipmap.collect_record;
        itemDataModel1.title = "领取记录";
        ItemDataModel itemDataModel2 = new ItemDataModel();
        itemDataModel2.type = 2;
        itemDataModel2.icon_id = R.mipmap.customer_service;
        itemDataModel2.title = "联系我们";
        ItemDataModel itemDataModel3 = new ItemDataModel();
        itemDataModel3.type = 3;
        itemDataModel3.icon_id = R.mipmap.scan;
        itemDataModel3.title = "扫一扫";
        ItemDataModel itemDataModel4 = new ItemDataModel();
        itemDataModel4.type = 4;
        itemDataModel4.icon_id = R.mipmap.about;
        itemDataModel4.title = "关于";
        itemDataModels.add(itemDataModel);
        itemDataModels.add(itemDataModel1);
        itemDataModels.add(itemDataModel2);
        itemDataModels.add(itemDataModel3);
        itemDataModels.add(itemDataModel4);
        return itemDataModels;
    }

    public boolean hasQQ(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pi = packageManager.getInstalledPackages(0);
        if (pi != null) {
            for (int i = 0; i < pi.size(); i++) {
                String pn = pi.get(i).packageName;
                if (pn.equals("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (EventBus.getDefault().isRegistered(this)) {
            return;
        }
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }


    @OnClick(R.id.login_or_out_bt)
    public void onViewClicked() {
        if (!ZSFGlobal.checkLogoutStatus(new ZSFGlobal.AccountCallBack() {
            @Override
            public void noneauth() {
                jumpToLoginPage();
            }
        })) {
            ZSFGlobal.logout();
        }
    }

    private void jumpToLoginPage() {
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        startActivity(intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MineFragmentPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @NeedsPermission(Manifest.permission.CAMERA)
    void jumpToScanActivity() {
        Intent intent = new Intent(getActivity(), ScanActivity.class);
        startActivity(intent);
    }

    @OnShowRationale(Manifest.permission.CAMERA)
    void showRationaleForCamera(PermissionRequest request) {
        new AlertDialog.Builder(getActivity())
                .setTitle("权限设置提醒")
                .setMessage("扫码需要打开摄像权限")
                .setPositiveButton("同意", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        request.proceed();
                        dialogInterface.dismiss();
                    }
                })
                .setNegativeButton("不同意", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        request.cancel();
                        dialogInterface.dismiss();
                    }
                })
                .show();
    }

    @OnPermissionDenied(Manifest.permission.CAMERA)
    void onCameraDenied() {
        ToastUtils.showLong("无法获得权限");
    }

    @OnNeverAskAgain(Manifest.permission.CAMERA)
    void onCameraNeverAskAgain() {
        ToastUtils.showLong("应用权限被拒绝,为了不影响您的正常使用，请在 权限 中开启对应权限");
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAccountLogin(AccountEventMessage message) {
        Logger.d("receive~~~");
        CircleImageView avatarImageView = containerView.findViewById(R.id.circleImageView3);
        if (message.isLogin()) {
            containerView.findViewById(R.id.info_container).setVisibility(View.VISIBLE);
            ((TextView) containerView.findViewById(R.id.nickname_tv)).setText(message.getUserModel().getPhone());
            avatarImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), AvatarSelectListActivity.class);
                    startActivityForResult(intent, AvatarSelectRequestCode);
                }
            });
            loginOrOutBt.setText("退出登录");
        } else {
            containerView.findViewById(R.id.info_container).setVisibility(View.GONE);
            containerView.findViewById(R.id.circleImageView3).setOnClickListener(null);
            loginOrOutBt.setText("立即登录");
        }
    }

}